/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package iie.tools;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 *
 * @author root
 */
public class XmlTools {

    //输入xml和key <parameter name="hdfsPath">http://10.128.11.11:9000</parameter>
    public static String getValueFromStrDGText = "";//final value for key
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(XmlTools.class);

    public static synchronized String getValueFromStrDGText(String xml, String name_key) {
        getValueFromStrDGText = "";
        Document doc = null;
        SAXReader reader = new SAXReader();
        try {
            //String code = xmlPath.get
            InputStream in = new ByteArrayInputStream(xml.getBytes("utf-8"));
            doc = reader.read(in);
        } catch (Exception ex) {
            logger.debug("getValueFromStrDGText error!", ex);
            return "";
        }
        if (doc != null) {
            Element rootEl = doc.getRootElement();
            getElValueDGText(rootEl, name_key);

            if (getValueFromStrDGText != null && !getValueFromStrDGText.equals("")) {
                return getValueFromStrDGText;
            }
        }
        return "";
    }

    private static synchronized void getElValueDGText(Element rootEl, String key) {
        if (rootEl.elements().size() > 0) {
            List<Element> childrenList = rootEl.elements();
            for (int i = 0; i < childrenList.size(); i++) {
                getElValueDGText(childrenList.get(i), key);
            }
        }
        String _name = rootEl.attributeValue("name");
        //logger.debug("xml'name: " + _name);
        if (_name != null && _name.equals(key)) {
            if (!getValueFromStrDGText.equals("")) {
                getValueFromStrDGText = getValueFromStrDGText + "|" + rootEl.getText();
            } else {
                getValueFromStrDGText = rootEl.getText();
            }
        }
    }

    //读subjobid <subjobid>9NRXLXcfSEehU2ecMKbm9A</subjobid>
    public static synchronized String getElValueFromStr(String xml, String key) {
        Document doc = null;
        SAXReader reader = new SAXReader();
        try {
            //String code = xmlPath.get
            InputStream in = new ByteArrayInputStream(xml.getBytes("utf-8"));
            doc = reader.read(in);
        } catch (Exception ex) {
            logger.debug("getElValueFromStr error!", ex);
            return "";
        }
        if (doc != null) {
            Element rootEl = doc.getRootElement();
            Element el = rootEl.element(key);
            String str = "";
            str = el.getText();
            return str;
        }
        return "";
    }

    public static synchronized String replace(String xml, Map<String, String> map) throws IOException {
        String subjobid = "";
        String instance = "";
        String operatorname = "";
        String status = "";
        String desc = "";
        String agentIP = "";
        String total = "";
        String complete = "";
        String time = "";

        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String key;
            String value;
            key = it.next().toString();
            value = map.get(key);
            if (key.equals("subjobid")) {
                subjobid = value;
            } else if (key.equals("instance")) {
                instance = value;
            } else if (key.equals("operatorname")) {
                operatorname = value;
            } else if (key.equals("status")) {
                status = value;
            } else if (key.equals("desc")) {
                desc = value;
            } else if (key.equals("total")) {
                total = value;
            } else if (key.equals("complete")) {
                complete = value;
            } else if (key.equals("time")) {
                time = value;
            } else if (key.equals("agentIP")) {
                agentIP = value;
            }
        }

        xml = xml.replaceAll("#subjobid#", subjobid);
        xml = xml.replaceAll("#instance#", instance);
        xml = xml.replaceAll("#operatorname#", operatorname);
        xml = xml.replaceAll("#status#", status);
        xml = xml.replaceAll("#desc#", desc);
        xml = xml.replaceAll("#agentIP#", agentIP);
        xml = xml.replaceAll("#total#", total);
        xml = xml.replaceAll("#complete#", complete);
        xml = xml.replaceAll("#time#", time);

        return xml;
    }

    /**
     * 获取1级节点的属性值
     *
     * @param xml 原xml
     * @param element 1子节点
     * @param attribute 子节点属性名
     * @return value 属性值
     */
    public static synchronized String getElementAttributeValue(String xml, String element, String attribute) {
        Document doc = null;
        String value = "";
        SAXReader reader = new SAXReader();
        try {
            InputStream in = new ByteArrayInputStream(xml.getBytes("utf-8"));
            doc = reader.read(in);
        } catch (Exception ex) {
            return "";
        }
        if (doc != null) {
            Element rootEl = doc.getRootElement();
            List<Element> ele1 = rootEl.elements();
            for (Element ele : ele1) {
                if (ele.getName().equals(element)) {
                    value = ele.attributeValue(attribute);
                }
            }
        }
        return value;
    }

    public static synchronized ArrayList<HashMap<String, String>> getIterationElementAttributeValue(String xml, String element1, String element2, String element3, String element4) throws DocumentException {
        String ip = "";
        String port = "";
        String username = "";
        String password = "";
        String filepath = "";
        ArrayList<HashMap<String, String>> ftpList = new ArrayList<HashMap<String, String>>();
        Document document = DocumentHelper.parseText(xml);
        Element rootElement = document.getRootElement();
        Element ele1 = rootElement.element(element1);
        Element ele2 = ele1.element(element2);
        Element operatorIdElement = ele2.element(element3);
        for (Iterator it = operatorIdElement.elementIterator(element4); it.hasNext();) {
            Element element = (Element) it.next();
            ip = element.elementTextTrim("ftpIP");
            port = element.elementTextTrim("ftpPort");
            username = element.elementTextTrim("username");
            password = element.elementTextTrim("password");
            filepath = element.elementTextTrim("filepath");
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("ip", ip);
            map.put("port", port);
            map.put("username", username);
            map.put("password", password);
            map.put("filepath", filepath);
            ftpList.add(map);
        }
        return ftpList;
    }

    //添加2级节点
    public static synchronized String addElement2(String xml, String element1, String element2, String value) {
        Document doc = null;
        SAXReader reader = new SAXReader();
        try {
            InputStream in = new ByteArrayInputStream(xml.getBytes("utf-8"));
            doc = reader.read(in);
        } catch (Exception ex) {
            return "";
        }
        if (doc != null) {
            Element rootEl = doc.getRootElement();
            Element el = rootEl.element(element1);
            Element tmp = el.addElement(element2);
            tmp.setText(value);
            return rootEl.asXML();
        }
        return "";
    }

    //添加2级节点
    public static synchronized String rmElement3(String xml, String element1, String element2, String element3) {
        Document doc = null;
        SAXReader reader = new SAXReader();
        try {
            InputStream in = new ByteArrayInputStream(xml.getBytes("utf-8"));
            doc = reader.read(in);
        } catch (Exception ex) {
            return "";
        }

        Element rootEl = null;
        boolean flag = false;
        if (doc != null) {
            rootEl = doc.getRootElement();
            Element el1 = rootEl.element(element1);
            Element el2 = el1.element(element2);
            Element el3 = el2.element(element3);
//            Element parent = el3.getParent();
            flag = el2.remove(el3);
        }
        if (flag) {
            return rootEl.asXML();
        } else {
            return "";
        }
    }

    public static void main(String[] args) {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                + "<requestParms>\n"
                + "    <subjobid>8NRXLXcfSEehU2ecMKbm9A</subjobid>\n"
                + "    <operator name=\"vY9Jw-FzNHR7HqlrwPvB7A\" class=\"AD.I.Collector\">\n"
                + "        <parameters>\n"
                + "			<parameter name=\"name\">ftpdownload</parameter>\n"
                + "			<parameter name=\"agentIP\">192.168.239.157:7011|192.168.239.158:7011|192.168.239.156:7011</parameter>\n"
                + "			<parameter name=\"type\">ftpdownload</parameter>\n"
                + "			<parameter name=\"timeout\">999999999</parameter>\n"
                + "\n"
                + "			<ftplist>\n"
                + "\n"
                + "				<ftp>\n"
                + "					<ftpIP>192.168.211.2</ftpIP>\n"
                + "					<ftpPort>21</ftpPort>\n"
                + "					<username>wxbftp</username>\n"
                + "					<password>wxbftp123%cys</password>\n"
                + "					<filepath>ToPlatForm/1_BK</filepath>\n"
                + "				</ftp>\n"
                + "\n"
                + "				<ftp>\n"
                + "					<ftpIP>192.168.233.14</ftpIP>\n"
                + "					<ftpPort>21</ftpPort>\n"
                + "					<username>wxbftp</username>\n"
                + "					<password>wxbftp123%cys</password>\n"
                + "					<filepath>ToPlatForm/1_BK</filepath>\n"
                + "				</ftp>\n"
                + "					\n"
                + "				<ftp>\n"
                + "					<ftpIP>192.168.234.18</ftpIP>\n"
                + "					<ftpPort>21</ftpPort>\n"
                + "					<username>wxbftp</username>\n"
                + "					<password>wxbftp123%cys</password>\n"
                + "					<filepath>ToPlatForm/1_BK</filepath>\n"
                + "				</ftp>	\n"
                + "\n"
                + "				<ftp>\n"
                + "					<ftpIP>192.168.211.2</ftpIP>\n"
                + "					<ftpPort>21</ftpPort>\n"
                + "					<username>wxbftp</username>\n"
                + "					<password>wxbftp123%cys</password>\n"
                + "					<filepath>ToPlatForm/0_BK</filepath>\n"
                + "				</ftp>\n"
                + "\n"
                + "				<ftp>\n"
                + "					<ftpIP>192.168.217.11</ftpIP>\n"
                + "					<ftpPort>21</ftpPort>\n"
                + "					<username>wxbftp</username>\n"
                + "					<password>wxbftp123%cys</password>\n"
                + "					<filepath>ToPlatForm/0_BK</filepath>\n"
                + "				</ftp>\n"
                + "\n"
                + "				<ftp>\n"
                + "					<ftpIP>192.168.233.53</ftpIP>\n"
                + "					<ftpPort>21</ftpPort>\n"
                + "					<username>wxbftp</username>\n"
                + "					<password>wxbftp123%cys</password>\n"
                + "					<filepath>ToPlatForm/0_BK</filepath>\n"
                + "				</ftp>\n"
                + "				\n"
                + "				<ftp>\n"
                + "					<ftpIP>192.168.216.11</ftpIP>\n"
                + "					<ftpPort>21</ftpPort>\n"
                + "					<username>wxbftp</username>\n"
                + "					<password>wxbftp123%cys</password>\n"
                + "					<filepath>ToPlatForm/1_BK</filepath>\n"
                + "				</ftp>\n"
                + "\n"
                + "				<ftp>\n"
                + "					<ftpIP>192.168.233.53</ftpIP>\n"
                + "					<ftpPort>21</ftpPort>\n"
                + "					<username>wxbftp</username>\n"
                + "					<password>wxbftp123%cys</password>\n"
                + "					<filepath>ToPlatForm/1_BK</filepath>\n"
                + "				</ftp>\n"
                + "\n"
                + "				<ftp>\n"
                + "					<ftpIP>192.168.218.11</ftpIP>\n"
                + "					<ftpPort>21</ftpPort>\n"
                + "					<username>wxbftp</username>\n"
                + "					<password>wxbftp123%cys</password>\n"
                + "					<filepath>ToPlatForm/1_BK</filepath>\n"
                + "				</ftp>\n"
                + "\n"
                + "				<ftp>\n"
                + "					<ftpIP>192.168.212.11</ftpIP>\n"
                + "					<ftpPort>21</ftpPort>\n"
                + "					<username>wxbftp</username>\n"
                + "					<password>wxbftp123%cys</password>\n"
                + "					<filepath>ToPlatForm/1_BK</filepath>\n"
                + "				</ftp>\n"
                + "				\n"
                + "				<ftp>\n"
                + "					<ftpIP>192.168.217.11</ftpIP>\n"
                + "					<ftpPort>21</ftpPort>\n"
                + "					<username>wxbftp</username>\n"
                + "					<password>wxbftp123%cys</password>\n"
                + "					<filepath>ToPlatForm/1_BK</filepath>\n"
                + "				</ftp>\n"
                + "\n"
                + "			</ftplist>\n"
                + "        </parameters>\n"
                + "        \n"
                + "        <context>\n"
                + "		<property name=\"queueName\" value=\"queueName\"/>\n"
                + "		<property name=\"tempHDFSPath\" value=\"hdfs://192.168.11.94:9000/datadock/scheduler/tempPath/qweqwe/\"/>\n"
                + "        </context>\n"
                + "        <datasets>\n"
                + "            <dataset name=\"inport\">\n"
                + "                <row name=\"inport1\">...</row>\n"
                + "            </dataset>\n"
                + "            <dataset name=\"outport\">\n"
                + "                <row name=\"outport1\">database.tablename</row>\n"
                + "            </dataset>\n"
                + "        </datasets>\n"
                + "    </operator>\n"
                + "</requestParms>";
//        String elementAttributeValue = getElementAttributeValue(xml, "operator", "name");
//        String addElement2 = addElement2(xml, "operator", "ftps", "#####");
        String uuid = UUID.randomUUID().toString().replace("-", "");
        logger.info("the uuid is: " + uuid);
        String subjobid = XmlTools.getElValueFromStr(xml, "subjobid");
        xml = xml.replace("<subjobid>" + subjobid + "</subjobid>", "<subjobid>" + uuid + "</subjobid>");

        //获取ftpList
        ArrayList<HashMap<String, String>> ftpList = new ArrayList<HashMap<String, String>>();
        try {
            ftpList = XmlTools.getIterationElementAttributeValue(xml, "operator", "parameters", "ftplist", "ftp");
        } catch (DocumentException ex) {
            logger.error("获取ftpList信息失败。" + ex.getMessage(), ex);
        }

        //解析ftpList
        String sendXml = "";
        if (!ftpList.isEmpty()) {
            //删除ftpList
            xml = XmlTools.rmElement3(xml, "operator", "parameters", "ftplist");
            //添加2级节点
            sendXml = XmlTools.addElement2(xml, "operator", "ftps", "#####");
            String ftps = "";
            String ftpip = "";
            for (int i = 0; i < ftpList.size(); i++) {
                HashMap<String, String> f = (HashMap<String, String>) ftpList.get(i);
                for (String str : f.keySet()) {
                    if (str.equals("ip")) {
                        ftpip = f.get(str);
                    }
                    ftps += "<ftp name=\"" + str + "\">" + f.get(str) + "</ftp>\n";
                }
                sendXml = sendXml.replace("<ftps>#####</ftps>", "<ftps>" + ftps + "</ftps>");
                sendXml = sendXml.replace("<parameter name=\"type\">ftpdownload</parameter>", "<parameter name=\"type\">" + ftpip + "</parameter>");

                System.out.println(sendXml);
                break;
            }

        }
//        System.out.println(xml);
    }
}
